package com.ruoyi.common.utils;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.http.HttpUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class MediaUtil {

    private static final Logger log = LoggerFactory.getLogger(MediaUtil.class);

    private static final String UPLOAD_URL = "http://testapi.youzhi.net/api/media/upload";

    private static final String TRANSCODE_URL = "http://testapi.youzhi.net/api/media/transcode";

    private static final String ADMIN_PLAY_URL = "http://testapi.youzhi.net/api/media/playInfo";

    public static String upload(String type, String name, String filepath, int autoTranscode) {
        String param = String.format("type=%s&name=%s&filepath=%s&autoTranscode=%s", type, name, filepath, autoTranscode);
        String rsp = HttpUtils.sendPost(UPLOAD_URL, param);
        log.info("upload file {}, rsp {}", filepath, rsp);
        Map<String, Object> info = JsonUtil.toMap(rsp);
        Map<String, Object> data = (Map) info.get("data");
        return data.get("vodId").toString();
    }

    public static void transcode(String vodId, Integer reTranscode) {
        String param = String.format("vodId=%s&reTranscode=%s", vodId, reTranscode);
        String rsp = HttpUtils.sendPost(TRANSCODE_URL, param);
        Map<String, Object> info = JsonUtil.toMap(rsp);
        int code = Integer.parseInt(info.get("status").toString());
        if (code != 200) {
            throw new BusinessException(info.get("message").toString());
        }
    }

    /**
     * @param vodId
     * @return
     */
    public static String getPlayUrl(String vodId) {
        String param = String.format("vodId=%s", vodId);
        String rsp = HttpUtils.sendPost(ADMIN_PLAY_URL, param);
        JSONObject jsonObject = new JSONObject(rsp);
        int status = jsonObject.getInt("status");
        if (status != 200) {
            throw new BusinessException(jsonObject.getString("message"));
        }
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray playInfos = data.getJSONArray("playInfos");
        if (playInfos.length() > 0) {
            JSONObject playInfo = playInfos.getJSONObject(0);
            String playUrl = playInfo.getString("playUrl");
            return playUrl;
        }
        throw new BusinessException("当前视频未准备好[" + vodId + "]");
    }

    public static void main(String[] args) {
        System.out.println(getPlayUrl("754b4b63346040c2a693eb08be361498"));
    }
}
